import { Md5 } from 'ts-md5'
import { request } from '@uni-helper/uni-promises'

const request2 = request('https://apis.map.qq.com')

export function toast(content: string, duration: number = 2000, icon: 'success' | 'loading' | 'error' | 'none' | 'fail' | 'exception' = 'none') {
    setTimeout(() => {
        uni.showToast({
            icon,
            title: content,
            duration,
        })
    }, 100)
}

// 节流
function Shake() {
    let timer = -1
    return function (obj: () => void, millisecond = 300) {
        clearTimeout(timer)
        timer = setTimeout(obj, millisecond) as unknown as number
    }
}

export const shake = Shake()

// 防抖
function Debounce() {
    const keys = [] as string[]
    return function (obj: () => void, millisecond = 300, key = '') {
        if (keys.includes(key))
            return
        const index = keys.length
        keys[index] = key
        setTimeout(() => {
            const index = keys.indexOf(key)
            keys.splice(index, 1)
        }, millisecond)
        obj()
        return true
    }
}

export const debounce = Debounce()

/**
 * wait等待
 */
export function wait(timeout = 1000) {
    return new Promise((resolve) => {
        setTimeout(resolve, timeout)
    })
}
/**
 *
 * @param price
 * @param type int: 整数部分 decimal: 小数部分
 * @returns
 */

export function getMoney(price: number, type: string) {
    if (!price)
        return ''
    if (type === 'int')
        return price.toString().split('.')[0]
    else if (type === 'decimal')
        // eslint-disable-next-line prefer-template
        return price.toString().split('.')[1] ? '.' + price.toString().split('.')[1] : '.00'
}

/**
 * 手机脱敏
 * @param phone
 */
export function filterPhone(phone: string) {
    return phone ? phone.replace(/(\d{3})(\d{4})(\d{3})/g, '$1****$3') : ''
}

/**
 * json对象转url参数
 * @param json
 */
export function jsonToParams(json: AnyObject) {
    let params = ''
    for (const key in json) {
        if (Object.prototype.hasOwnProperty.call(json, key))
            params += `${key}=${json[key]}&`
    }
    return params
}

/*
 * 通过坐标逆向获取位置信息
 */
export async function amapRegeo(data: {
    location: string
}) {
    const SIG = new Md5().appendStr(`/ws/geocoder/v1/?key=DOHBZ-SPX3J-SQOFQ-XLIHQ-WSR2Z-BVB42&location=${data.location}VK7O6fR92i5ODEtIschycfJR7smOrvCq`).end()
    return await request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        method: 'GET',
        data: {
            location: data.location,
            key: 'DOHBZ-SPX3J-SQOFQ-XLIHQ-WSR2Z-BVB42',
            sig: SIG,
        },
    }) as {
        result: {
            address: string
        }
    }
}

// 本地文件转base64
export function wxfileTobase64(url: string, ishead = false) {
    return new Promise((reslove, reject) => {
        uni.getFileSystemManager().readFile({
            filePath: url, // 选择图片返回的相对路径
            encoding: 'base64', // 编码格式
            success: (res) => { // 成功的回调
                reslove((ishead ? 'data:image/jpeg;base64,' : '') + res.data)
            },
            fail: (err) => {
                reject(err)
            },
        })
    })
}

/**
 * 将参数字符串转换为 JSON 对象
 *
 * @param params 参数字符串
 * @returns 返回 JSON 对象
 */
export function paramsToJson(params: string) {
    params = params.includes('?') ? params.split('?')[1] : params
    const paramsJson: Record<string, string> = {}
    const list = params.split('&')
    list.forEach((item) => {
        const arr = item.split('=')
        if (arr[0] && arr[1])
            paramsJson[decodeURIComponent(arr[0])] = decodeURIComponent(arr[1])
    })
    return paramsJson
}

// 身份证转年龄
export function getCardAge(identityCard: string) {
    const len = (`${identityCard}`).length
    // 没有身份证或是 身份证号码不合法 （只能为15位或18位）
    if (len === 0 || ((len !== 15) && (len !== 18)))
        return 0

    let strBirthday = ''
    if (len === 18) // 处理18位的身份证号码从号码中得到生日和性别代码
        strBirthday = `${identityCard.substr(6, 4)}/${identityCard.substr(10, 2)}/${identityCard.substr(12, 2)}`

    if (len === 15)
        strBirthday = `19${identityCard.substr(6, 2)}/${identityCard.substr(8, 2)}/${identityCard.substr(10, 2)}`

    // 时间字符串里，必须是“/”
    const birthDate = new Date(strBirthday)
    const nowDateTime = new Date()
    let age = nowDateTime.getFullYear() - birthDate.getFullYear()
    // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
    if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() === birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate()))
        age--

    return age
}
